package routers

import (
	"encoding/json"
	"net/http"
	"strconv"

	"shqsoft.cn/pasnj/base"
	"shqsoft.cn/pasnj/popedom"

	"github.com/labstack/echo"
)

//ExportXlsxRouter 导出数据到xlsx
func ExportXlsxRouter(c echo.Context) error {
	caption := c.Param("Caption")
	if caption == "" {
		caption = "数据导出"
	}
	daoName := c.Param("DaoName")
	if daoName == "" {
		return echo.NewHTTPError(http.StatusBadRequest, "daoName不能为空！")
	}
	var whereCauses []base.WhereCause
	jsonStr := c.FormValue("WhereCauses")
	if jsonStr != "" {
		err := json.Unmarshal([]byte(jsonStr), &whereCauses)
		if err != nil {
			return echo.NewHTTPError(http.StatusBadRequest, err.Error())
		}
	}
	var columnHeaders []base.ColumnHeader
	jsonStr = c.FormValue("ColumnHeaders")
	if jsonStr != "" {
		err := json.Unmarshal([]byte(jsonStr), &columnHeaders)
		if err != nil {
			return echo.NewHTTPError(http.StatusBadRequest, err.Error())
		}
	}
	var orderItems []base.OrderItem
	jsonStr = c.FormValue("OrderItems")
	if jsonStr != "" {
		err := json.Unmarshal([]byte(jsonStr), &orderItems)
		if err != nil {
			return echo.NewHTTPError(http.StatusBadRequest, err.Error())
		}
	}
	dao, err := base.GetDao(daoName)
	if err != nil {
		return echo.NewHTTPError(http.StatusBadRequest, err.Error())
	}
	permIDStr := c.FormValue("PermID")
	if permIDStr == "" {
		return echo.NewHTTPError(http.StatusBadRequest, "PermID不能为空！")
	}
	permID, err := strconv.Atoi(permIDStr)
	if err != nil {
		return echo.NewHTTPError(http.StatusBadRequest, "PermID必须为整数！")
	}
	userIDStr := c.FormValue("UserID")
	if userIDStr == "" {
		return echo.NewHTTPError(http.StatusBadRequest, "UserID不能为空！")
	}
	userID, err := strconv.Atoi(userIDStr)
	if err != nil {
		return echo.NewHTTPError(http.StatusBadRequest, "UserID必须为整数！")
	}
	pTypes, err := popedom.GetUserPermissionTypes(userID, permID)
	if err != nil {
		return echo.NewHTTPError(http.StatusBadRequest, err.Error())
	}
	var flag bool
	for _, p := range pTypes {
		if p == "4" {
			flag = true
		}
	}
	if daoName == "INDI_SAVE_ACCO" && flag {
		return echo.NewHTTPError(http.StatusBadRequest, "无法导出数据！")
	}
	xlsx := base.NewXlsx(dao, whereCauses, orderItems, columnHeaders)
	buff, err := xlsx.Export(userID, pTypes...)
	if err != nil {
		return echo.NewHTTPError(http.StatusBadRequest, err.Error())
	}
	// fileName := caption + ".xlsx"
	// log.Debug(buff)

	var pName string
	row := base.DB.Raw("SELECT PermissionName FROM T_Permission WHERE ID=? ", permID).Row()
	err = row.Scan(&pName)
	//fileName := caption + ".xlsx"
	fileName := pName + ".xlsx"

	c.Response().Header().Set("Content-Type", "application/vnd.ms-excel")
	c.Response().Header().Set("Content-Disposition", "attachment; filename="+fileName)
	c.Response().Write(buff.Bytes())
	return nil
}
